package com.example.chenduoyun.safe.activity;
/**
 * @author cdy
 */

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.chenduoyun.safe.R;
import com.example.chenduoyun.safe.utils.ConstantValue;
import com.example.chenduoyun.safe.utils.SpUtils;
import com.example.chenduoyun.safe.utils.ToastUtil;
import com.example.chenduoyun.safe.view.SettingItemView;

public class Setup2Activity extends BaseSetupActivity implements View.OnClickListener {

    private SettingItemView siv_sim_bound;
    private int MY_PERMISSION_REQUEST_CODE = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup2);

        findViewById(R.id.btn_next).setOnClickListener(this);
        findViewById(R.id.btn_pre).setOnClickListener(this);
        initUI();
    }

    @Override
    public void showNextPage() {
        judgeNextPage();
    }

    @Override
    public void showPrePage() {
        judgePerPage();
    }

    private void initUI() {
        siv_sim_bound = findViewById(R.id.siv_sim_bound);
        final String sim_number = SpUtils.getString(this, ConstantValue.SIM_NUMBER, "");
        if (TextUtils.isEmpty(sim_number)) {
            siv_sim_bound.setCheck(false);
        } else {
            siv_sim_bound.setCheck(true);
        }
        siv_sim_bound.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                judgeNextPage();
                break;
            case R.id.btn_pre:
                judgePerPage();
                break;
            case R.id.siv_sim_bound:
                boolean isCheck = siv_sim_bound.isCheck();
                siv_sim_bound.setCheck(!isCheck);
                if(checkSelfPermissionAll(new String[]{Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.RECEIVE_BOOT_COMPLETED})){
                    if (!isCheck) {
                        addPhoneSim();
                    } else {
                        SpUtils.remove(getApplicationContext(), ConstantValue.SIM_NUMBER);
                    }
                }else{
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.READ_PHONE_STATE,
                                    Manifest.permission.RECEIVE_BOOT_COMPLETED}, MY_PERMISSION_REQUEST_CODE);
                }
                break;
            default:
                break;
        }
    }

    private void addPhoneSim(){
        TelephonyManager manager = (TelephonyManager)
                getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        String simSerialNumber = manager.getSimSerialNumber();
        Log.i("cdy", "onClick: "+simSerialNumber);
        SpUtils.putString(getApplicationContext(),ConstantValue.SIM_NUMBER,simSerialNumber);
    }

    private boolean checkSelfPermissionAll(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isPermission = true;
            for (int grant : grantResults) {
                //判断是否所有权限都已经授权
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isPermission = false;
                    break;
                }
                if (isPermission) {
                    addPhoneSim();
                }else{
//                     弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
//                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
//                    builder.setMessage("备份通讯录需要访问")
//                            .setPositiveButton("设置", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialogInterface, int i) {
//                                    Intent intent=new Intent();
//                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//                                    intent.addCategory(Intent.CATEGORY_DEFAULT);
//                                    intent.setData(Uri.parse("package:" + getPackageName()));
//                                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
//                                    intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//                                    startActivity(intent);
//                                }
//                            })
//                            .setNegativeButton("退出",null);
//                    builder.show();
                }
            }
        }
    }

    private void judgePerPage(){
        Intent intent = new Intent(getApplicationContext(), Setup1Activity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.pre_in_anim, R.anim.pre_out_anim);
    }
    private void judgeNextPage(){
        String string = SpUtils.getString(getApplicationContext(), ConstantValue.SIM_NUMBER, "");
        if (!TextUtils.isEmpty(string)) {
            Intent intent = new Intent(getApplicationContext(), Setup3Activity.class);
            startActivity(intent);
            finish();
            overridePendingTransition(R.anim.next_in_anim, R.anim.next_out_anim);
        } else {
            ToastUtil.show(getApplicationContext(), "请绑定SIM卡");
        }
    }
}
